package com.fuint.module.schedule;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fuint.common.service.MessageService;
import com.fuint.common.service.WeixinService;
import com.fuint.common.util.LogUtils;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.repository.model.MessageParams;
import com.fuint.repository.model.MtMessage;
import com.fuint.utils.StringUtil;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.util.JsonUtil;

import java.util.Date;
import java.util.List;

/**
 * 会员消息定时任务
 */
@EnableScheduling
@Component("messageJob")
@RequiredArgsConstructor
public class MessageJob {
    /**
     * 消息服务接口
     */
    private final MessageService messageService;
    /**
     * 微信服务接口
     */
    private final WeixinService weixinService;
    private final Environment environment;
    /**
     * 一次最多发送消息数量
     **/
    private final static int MAX_SEND_NUM = 50;

    @Scheduled(cron = "${message.job.time}")
    @Transactional(rollbackFor = Exception.class)
    public void dealMessage() throws BusinessCheckException {
        String theSwitch = environment.getProperty("message.job.switch");
        if (theSwitch != null && theSwitch.equals("1")) {
            LogUtils.info("--- MessageJobStart!!! ---");
            List<MtMessage> dataList = messageService.getNeedSendList();
            if (CollUtil.isNotEmpty(dataList)) {
                int dealNum = 0;
                for (MtMessage mtMessage : dataList) {
                    String params = mtMessage.getParams();
                    MessageParams paramsBean = JSONUtil.toBean(params, MessageParams.class);

                    LogUtils.info("--- 待处理的消息:{} ---", paramsBean);

                    String page = mtMessage.getPage();
                    String templateId = mtMessage.getTemplateId();
                    String touser = mtMessage.getTouser();

                    LogUtils.info("page:{}, templateId:{}, touser:{}", page, templateId, touser);

                    paramsBean.setTemplate_id(templateId);
                    paramsBean.setPage(page);
                    paramsBean.setTouser(touser);

                    try {
                        ObjectMapper objectMapper = new ObjectMapper();
                        String paramsBeanToStr = objectMapper.writeValueAsString(paramsBean);
                        LogUtils.info("paramsBean:", paramsBeanToStr);

                        Date nowTime = new Date();

                        // 如果到了发送时间，发送并删除该条消息
                        if (dealNum <= MAX_SEND_NUM && mtMessage.getSendTime().before(nowTime) && StringUtil.isNotEmpty(params)) {
                            // wx订阅消息如果要改全局通用在这
                            boolean result = weixinService.doSendSubscribeMessage(0, paramsBeanToStr);
                            messageService.sendMessage(mtMessage.getId(), result);
                            dealNum++;
                        }
                    } catch (Exception e) {
                        LogUtils.error("发消息报错:", e);
                    }
                }
            }
            LogUtils.info("MessageJobEnd!!!");
        }
    }
}
